﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using MadLibrary.Collections;

namespace MadLibrary.Managing
{
    /// <summary>Class.</summary>
    /// <typeparam name="T">Generic type parameter.</typeparam>
    public class DataManager<T> : Collection<T> where T : class, IManagable, new()
    {
        /// <summary>Gets or sets the full pathname of the file.</summary>
        /// <value>The full pathname of the file.</value>
        public string Path { get; set; }

        /// <summary>Initializes a new instance of the DataManager class.</summary>
        public DataManager()
        {
            this.Path = string.Empty;
        }

        /// <summary>Initializes a new instance of the DataManager class.</summary>
        /// <param name="Path">Full pathname of the file.</param>
        public DataManager(string Path)
        {
            this.Path = Path;
        }

        /// <summary>Saves this object.</summary>
        public void Save()
        {
            BinaryWriter bw = new BinaryWriter(File.Open(this.Path, FileMode.OpenOrCreate));
            foreach (IManagable im in this)
            {
                bw.Write(im.Save());
            }
            bw.Close();
        }

        /// <summary>Loads this object.</summary>
        public void Load()
        {
            T a = new T();
            byte[] data = new byte[(a as IManagable).Size];
            BinaryReader br = new BinaryReader(File.Open(this.Path, FileMode.Open));
            int i = 0;
            while (i != br.BaseStream.Length - 1)
            {
                i += br.Read(data, i, (a as IManagable).Size);
                (a as IManagable).Load(data);
                this.Add(a);
            }
            br.Close();
        }
    }
}